import React from 'react';
import { Modal, Form, Input, InputNumber, Select } from 'antd';


import { PERIOD_OPTIONS, MODE_OPTIONS, STEP_INTERVAL_OPTIONS } from 'src/core/common'


class PlanDialog extends React.Component {
  constructor(props) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);

    this.formRef = React.createRef();
    this.state = { confirmLoading: false };
  }

  async handleSubmit() {
    try {
      const values = await this.formRef.current.validateFields();

      this.onFinish(values);
    } catch (err) {
      console.log('validateFields error', err);
    }
  }

  async onFinish(values) {
    const plan = { ...this.props.plan, name: values.name }

    const result = this.props.onSubmit && this.props.onSubmit(plan);
    if (result instanceof Promise) {
      this.setState({ confirmLoading: true });
      result.finally(() => {
        this.setState({ confirmLoading: false });
      });
    }
  }

  render() {
    const { edit, plan, open, onCancel } = this.props;
    const initialValues = plan;

    const selectAfter = (
      <Select
        style={{
          width: 60,
        }}
        value={plan.interval_unit}
        options={STEP_INTERVAL_OPTIONS} disabled />
    );

    return (
      <Modal title={edit ? "编辑查询计划" : "新建查询计划"}
        zIndex={1020}
        open={open}
        confirmLoading={this.state.confirmLoading}
        onCancel={onCancel}
        onOk={this.handleSubmit}>
        <Form
          ref={this.formRef}
          colon={false}
          initialValues={initialValues}>
          <Form.Item
            label="名称"
            name="name"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input type="text" />
          </Form.Item>

          <Form.Item
            label="周期"
            name="picker_type">
            <Select options={PERIOD_OPTIONS} disabled />
          </Form.Item>

          <Form.Item
            label="模式"
            name="mode_type">
            <Select options={MODE_OPTIONS} disabled />
          </Form.Item>

          <Form.Item
            label="间隔"
            name="data_interval">
            <InputNumber addonAfter={selectAfter} disabled />
          </Form.Item>

          <Form.Item
            label="测量点"
            name="point_list">
            <Input type="text" disabled />
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default PlanDialog